package com.vogue.flowmeter.ui.activity;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.maning.mndialoglibrary.MProgressDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.vogue.flowmeter.R;
import com.vogue.flowmeter.api.entity.ApiUpdateApkEntity;
import com.vogue.flowmeter.api.entity.BaseResponse;
import com.vogue.flowmeter.api.event.DownloadMessageEvent;
import com.vogue.flowmeter.api.event.RecordMessageEvent;
import com.vogue.flowmeter.api.retrofit.NetWorkManager;
import com.vogue.flowmeter.ui.fragment.DashboardFragment;
import com.vogue.flowmeter.update.BgUpdate;
import com.vogue.flowmeter.util.AppUtils;
import com.vogue.flowmeter.util.DeviceIdUtil;
import com.vogue.flowmeter.util.FileUtils;
import com.vogue.flowmeter.util.PrefsUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.IOException;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * 关于
 */
public class AboutActivity extends AppCompatActivity {
    private TextView tvDeviceId;
    protected static int OVERLAY_PERMISSION_REQ_CODE=110;
    private ProgressDialog mProgressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_about);
        ActionBar actionBar=getSupportActionBar();
        if(actionBar != null){
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        setTitle("关于我们");
        tvDeviceId=findViewById(R.id.tv_device_id);
        //初始化进度对话框
        mProgressDialog =new ProgressDialog(this);
        //8.0系统加强后台管理，禁止在其他应用和窗口弹提醒弹窗，如果要弹，必须使用TYPE_APPLICATION_OVERLAY，否则弹不出
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mProgressDialog.getWindow().setType((WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY));
        }else {
            mProgressDialog.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
        }
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置水平进度条
        String apkLocalFilePath=PrefsUtils.getInstance(AboutActivity.this).get("apkLocalFilePath","");
        if (FileUtils.fileExists(apkLocalFilePath)){
            FileUtils.deleteFile(new File(apkLocalFilePath));
        }
        if ( Build.VERSION.SDK_INT>= 23 ) {
            if (Settings.canDrawOverlays(this)) {
                checkApk();
            }else {
                //Toast.makeText(this, "没有悬浮窗权限m,去开启悬浮窗权限", Toast.LENGTH_LONG).show();
                new AlertDialog.Builder(this)
                        .setTitle("授权提醒")
                        .setMessage("没有悬浮窗权限,去开启悬浮窗权限")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent  intent=new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                                intent.setData(Uri.parse("package:" + getPackageName()));
                                startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
                            }
                        })
                        .show();
            }
        }else {
            checkApk();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // back button
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 检查apk更新
     */
    private void checkApk(){
        RxPermissions rxPermissions=new RxPermissions(this);
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_PHONE_STATE,Manifest.permission.INTERNET).subscribe(aBoolean -> {
            if (aBoolean){

                String uniqueId= DeviceIdUtil.getDeviceId(this);
                tvDeviceId.setText("设备唯一码："+uniqueId);

                ApiUpdateApkEntity updateApk=new ApiUpdateApkEntity();
                int code=AppUtils.getAppVersionCode(AboutActivity.this,"com.vogue.ble");
                updateApk.setCode(code);
                NetWorkManager
                        .getInstance()
                        .getBleApiService()
                        .getUpdateApk(updateApk)
                        .subscribeOn(Schedulers.io())
                        .doOnSubscribe(disposable -> {
                            MProgressDialog.showProgress(AboutActivity.this, "加载中...");
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new DefaultObserver<ResponseBody>() {
                            @Override
                            public void onNext(ResponseBody response) {
                                MProgressDialog.dismissProgress();
                                try {
                                    String body=response.string();
                                    Log.e(AboutActivity.class.getName(),""+body);
                                    BaseResponse<ApiUpdateApkEntity> res= JSON.parseObject(body,new TypeReference<BaseResponse<ApiUpdateApkEntity>>(ApiUpdateApkEntity.class){});
                                    if (res.getCode()==0&&res.getData()!=null){
                                        if (FileUtils.isSdCardAvailable()){
                                            String filePath = FileUtils.getDataPath(getApplicationContext());
                                            PrefsUtils.getInstance(AboutActivity.this).put("apkLocalFilePath",filePath+"/"+res.getData().getFileName());
                                            Log.e(AboutActivity.class.getName(),filePath+"/"+res.getData().getFileName());

                                            BgUpdate.downloadForUpdate(AboutActivity.this, res.getData().getApkUrl(), filePath, res.getData().getFileName(),true);
                                        }
                                    }else {
                                        showToast(res.getMsg());
                                        Log.e(AboutActivity.class.getName(),""+res.getMsg());
                                    }
                                }catch (IOException i){
                                    showToast(i.getMessage());
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                showToast(e.getMessage());
                                MProgressDialog.dismissProgress();
                            }

                            @Override
                            public void onComplete() {
                                MProgressDialog.dismissProgress();
                            }
                        });
            }else {
                showToast("无法获取信息");
            }
        });

        //发送事件出去
        RecordMessageEvent recordMessageEvent = new RecordMessageEvent("checkApk", "检查apk更新");
        EventBus.getDefault().post(recordMessageEvent);
    }

    /**
     * 订阅消息  更新进度
     *
     * @param event
     */
    @Subscribe
    public void onUpdateMessageEvent(DownloadMessageEvent event) {
        Log.e(DashboardFragment.class.getName(), event.toString());

        if (event.getProgress()>=100&&event.isStatus()){
            if (mProgressDialog.isShowing()){
                mProgressDialog.setProgress(100);
                mProgressDialog.dismiss();

            }
            mProgressDialog.dismiss();
        }else {
            mProgressDialog.setTitle("下载进度");
            mProgressDialog.setProgress(event.getProgress());
            if (!mProgressDialog.isShowing())
                mProgressDialog.show();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
            if (Build.VERSION.SDK_INT >= 23) {
                if (!Settings.canDrawOverlays(this)) {
                    Toast.makeText(this, "权限授予失败，无法开启悬浮窗", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(this, "悬浮弹窗权限授予成功！", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    /**
     *
     * @param msg
     */
    protected void showToast(String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(AboutActivity.this, msg, Toast.LENGTH_LONG).show();
            }
        });
    }
}